package net.xdclass.xdclassredis.controller;

import net.xdclass.xdclassredis.config.CaptchaConfig;
import net.xdclass.xdclassredis.model.res.ApiResult;
import net.xdclass.xdclassredis.util.CommonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.util.concurrent.TimeUnit;

/**
 * @Author Mr. MaYaYun
 * @Data 2021/7/20 13:33
 */

@RestController
@RequestMapping("/api/captcha")
public class CaptchaController {


    private static long timeOut = 1000*60*2;

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private CaptchaConfig captchaConfig;


    @GetMapping("/get_captcha")
    public void getCaptcha(HttpServletRequest request, HttpServletResponse response){

        String captchaText = captchaConfig.kaptcha().createText();//获取验证码的数字

        String key = getCaptchaKey(request);//设置key为标记

        redisTemplate.opsForValue().set(key,captchaText,timeOut, TimeUnit.MILLISECONDS);//设置验证码加过期时间保存在redis
        BufferedImage image = captchaConfig.kaptcha().createImage(captchaText);//验证码变成图片形式
        ServletOutputStream outputStream = null;

        try {
            outputStream = response.getOutputStream();//开启输出流
            ImageIO.write(image,"jpg",outputStream);//输出出去
            outputStream.flush();//清掉
            outputStream.close();//关闭

        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @GetMapping
    public ApiResult sendCode(@RequestParam(value = "to",required = true) String to,
                              @RequestParam(value = "captcha",required = true) String captcha,
                              HttpServletRequest request){
        String key = getCaptchaKey(request);
        String cacheCaptcha = redisTemplate.opsForValue().get(key);
        //输入的验证码不空，用传输来的和redis里比较的不空，两者比较一致
        if (captcha != null && cacheCaptcha != null && cacheCaptcha.equalsIgnoreCase(captcha)){
            redisTemplate.delete(key);
            //TODO 发送短信验证码
            return ApiResult.newSuccess("成功");
        }else {
            return ApiResult.newError("失败");
        }
    }

    private String getCaptchaKey(HttpServletRequest request){

        String ip = CommonUtils.getIpAddr(request);//获取ip地址
        String userAgent = request.getHeader("User-Agent");//获取请求的头部信息（浏览器）
        String key = "user-service:captcha:"+CommonUtils.MD5(ip + userAgent);
        return key;
    }

}
